<template>
  <JVxeTable
    ref="tableRef"
    stripe
    toolbar
    keepSource
    rowNumber
    rowSelection
    asyncRemove
    dragSort
    :sync-resize="activeKey"
    :checkboxConfig="{ range: true }"
    :disabledRows="{ isPk: [true] }"
    :loading="loading"
    :disabled="disabled"
    :columns="columns"
    :dataSource="dataSource"
    @value-change="handleValueChange"
    @removed="handleRemove"
  />
</template>

<script lang="ts" setup>
  import { ref, computed, onUnmounted, watch, nextTick } from "vue"
  import { JVxeColumn, JVxeTableInstance } from "/@/components/jeecg/JVxeTable/types"
  import { batchDeleteField } from "/@/api/infra/diyForm"
  import { fieldColumns } from "./data"
  import { useMessage } from "/@/hooks/web/useMessage"
  const { createMessage } = useMessage()

  const tableRef = ref<JVxeTableInstance>()
  const loading = ref(false)
  const disabled = ref(false)
  const isInit = ref(false)
  const dataSource = ref<any[]>([])
  const columns = ref<JVxeColumn[]>(fieldColumns)
  const props = defineProps({
    // 子组件接收父组件传递过来的值
    rowId: String,
    formField: Array as PropType<any[]>,
    activeKey: String,
  })

  const getData = () => {
    return tableRef.value!.getTableData()
  }

  const handleValueChange = (event) => {
    // 抛出事件会出现  TypeError: Cannot read properties of null
    // 由于j-vxe-table对事件进行了处理, 可以在最外层接收到事件
    // console.log("handleValueChange, event: ", event.$table.data)
    // const data = tableRef.value!.getTableData()
  }

  const validate = async (callback: Function) => {
    const values = tableRef.value!.getTableData()
    for (const item in values) {
      const errMap = await tableRef.value!.validateTable(values[item])
      if (errMap) {
        console.log("表单验证未通过：", { errMap })
        if (callback) {
          callback()
        }
        await tableRef.value!.validateTable()
        return false
      }
    }
    return true
  }

  onUnmounted(() => {
    console.log("onUnmounted PageAttributeColumn")
  })

  watch(
    () => props.formField,
    async (val) => {
      try {
        if (val && !isInit.value && tableRef.value) {
          // dataSource.value = val
          tableRef.value.removeRows(val)
          tableRef.value.addRows(val)
          isInit.value = true
        }
      } catch (err) {
        console.error(err)
      }
    },
    { deep: true, immediate: true }
  )

  const handleRemove = async (event) => {
    const hideLoading = createMessage.loading("删除中…", 0)
    try {
      let ids = []
      event.deleteRows.forEach((x) => {
        if (!x.id.includes("row")) {
          ids.push(x.id)
        }
      })
      if (ids.length == 0) {
        return
      }
      await tableRef.value!.removeSelection()
    } catch (e) {
      createMessage.warn("删除失败！")
    } finally {
      await tableRef.value!.removeSelection()
      hideLoading()
    }
  }

  defineExpose({ getData, validate })
</script>
